/*
 * @Author: Author && Email
 * @Date: 2024-03-14 19:44:15
 * @LastEditors: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @LastEditTime: 2024-03-19 17:48:51
 * @FilePath: \MDK-ARMd:\WorkSpace\PRJ\Washing_machine\software\Washing_machine_V1\User\main_user.c
 * @Description: 
 * 
 * Copyright (c) 2024 by ${git_name_email}, All Rights Reserved. 
 */
#include "main_user.h"
#include "bmp.h"

uint16_t temp_wait_conv = 0;
uint16_t temp_bk;
void main_init(void)
{
	HAL_Delay(50);
	
	bsp_encoder_init();	/* 编码器初始化 */
	bsp_adc_init();		/* ADC初始化 */
	POWER_ON();

	api_hard_init();
	api_key_init();
	
	OLED_Init();
	OLED_ColorTurn(0);//0正常显示，1 反色显示
	OLED_DisplayTurn(0);//0正常显示 1 屏幕翻转显示
	OLED_ShowString(8, 24, (uint8_t*)"SYSTEM OPEN...", 16, 1);
	OLED_Refresh();
	api_display_task = api_update_page1;
	
	ds18b20_start_convert();	/* 进行一次温度转换 */
	HAL_Delay(800);
	g_hard.temp = ds18b20_temp_get();	/* 温度获取 */
	g_hard.power_on = 1;	/* 开机 */
	/* 开启定时器16更新中断 1ms定时 */
	__HAL_TIM_CLEAR_IT(&htim16, TIM_IT_UPDATE);
	HAL_TIM_Base_Start_IT(&htim16);
	OLED_Clear();
}

void main_user(void)
{
	main_init();
	
	while(1)
	{
		bsp_adc_calc();						/* ADC计算值获取 */
		if(temp_wait_conv >= 750)
		{
			temp_bk = ds18b20_temp_get();	/* 温度获取 */
			if(temp_bk > g_hard.temp)
			{
				if(temp_bk-g_hard.temp <= 300)
				{
					g_hard.temp = temp_bk;
				}
			}
			else
			{
				if(g_hard.temp-temp_bk <= 300)
				{
					g_hard.temp = temp_bk;
				}
			}
			ds18b20_start_convert();	/* 进行一次温度转换 */
			temp_wait_conv = 0;
		}
		api_display_task();
		api_wash_task();
	}
}


/**
 * @description: 定时器中断回调函数
 * @param {TIM_HandleTypeDef} *htim
 * @return {*}
 */
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
	static uint16_t cnt_500ms = 0;
	static uint16_t filter_key = 0;
	/* TIM16 1ms定时器 */
	if(htim->Instance == TIM16)
	{
		temp_wait_conv++;
		api_hard_read();		/* 读取硬件接口 */
		api_hard_load();		/* 加载硬件接口 */
    	bsp_encoder_task();		/* 编码器速度计算 */
		motor_speed_task();		/* 电机速度控制 */
		motor_hard_task();		/* 电机控制参数对接到电机硬件层接口 */
		api_key_scan();			/* 按键扫描任务 */
		wash_sw_timer_isr();
		cnt_500ms++;
		if(cnt_500ms >= 1000)
		{
			g_hard.mcu_led = !g_hard.mcu_led;
			cnt_500ms = 0;
		}
		if(g_hard.power_key && filter_key!=0)
		{
			filter_key++;
			if(filter_key >= 50)
			{
				g_hard.power_on = 0;
			}
		}
		else if(!g_hard.power_key)
		{
			filter_key = 1;
		}
	}
	else if(htim->Instance == TIM1)	/* 编码器脉冲计数器溢出中断 */
	{
		bsp_encoder_over_flow_isr();
	}
}
